<template>
  <page-header-wrapper :title="false">
    <el-card class="box-card">
      <div slot="header" class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :span="6">
              <a-form-item label="标题">
                <a-input v-model="queryParam.title" placeholder="请输入标题" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="分类">
                <a-tree-select
                  v-model="queryParam.categoryId"
                  :replaceFields="{children:'children', title:'name', key:'id', value: 'id' }"
                  :tree-data="treeData"
                  placeholder="请选择分类"
                  tree-default-expand-all
                  :dropdownMatchSelectWidth = "true"
                  :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
                >
                  <span slot="title" slot-scope="{ key, value }" style="color: #08c">
                    {{ value }}
                  </span>
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="状态">
                <a-select v-model="queryParam.state" placeholder="请选择状态">
                  <a-select-option v-for="(item,index) in stateList" :key="index" :value="item.value">
                    {{ item.label }}
                  </a-select-option>
                </a-select>

              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-button style="margin-right: 8px" type="primary" @click="query">查询</a-button>
              <a-button type="danger" @click="reset">重置</a-button>
            </a-col>
            <a-col :offset="16" :span="8" style="text-align: right;">
              <span class="table-page-search-submitButtons">
                <a-button icon="plus" style="margin-right: 8px" type="primary" @click="handleAdd">新建</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <el-table
        :data="tableData"
        border
        style="width: 100%">
        <el-table-column width="150" label="分类" prop="categoryName" />
        <el-table-column width="150" label="标题" prop="title" />
        <el-table-column width="150" label="简介" prop="brief" />
        <el-table-column width="150" label="考试时间" prop="examDate" align="center" />
        <el-table-column width="150" label="报考费用" prop="fee" align="center" />
        <el-table-column width="150" label="抵扣金币" prop="discountCoin" align="center" />
        <el-table-column width="150" label="考试区域" prop="cityName" align="center" />
        <el-table-column width="150" label="考试地点" prop="address" align="center" />
        <el-table-column width="150" label="状态" align="center" >
          <template slot-scope="scope">
            <el-tag v-if="parseInt(scope.row.state) === 1">激活</el-tag>
            <el-tag v-if="parseInt(scope.row.state) === 2" type="danger">冻结</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="150" label="排序号" prop="sortOrder" align="center"/>
        <el-table-column width="150" label="创建时间" prop="createTime" align="center" />
        <el-table-column width="150" label="更新时间" prop="updateTime" align="center" />
        <el-table-column width="210" fixed="right" align="center" label="操作" >
          <template slot-scope="scope">
            <el-link
              :underline="false"
              type="primary"
              @click="handleEdit(scope.row)">编辑
            </el-link>
            <el-link
              v-if="parseInt(scope.row.state) === 2"
              :underline="false"
              style="margin-left:10px;"
              type="success"
              @click="handleStatus(scope.row)">激活
            </el-link>
            <el-link
              v-if="parseInt(scope.row.state) === 1"
              :underline="false"
              style="margin-left:10px;"
              type="danger"
              @click="handleStatus(scope.row)">冻结
            </el-link>
            <el-link
              :underline="false"
              style="margin-left:10px;"
              type="primary"
              @click="handlePreview(scope.row)">预览
            </el-link>
            <el-link
              :underline="false"
              style="margin-left:10px;"
              type="info"
              @click="handleCopy(scope.row)">复制
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <div style="display: flex;justify-content: flex-end;margin: 20px 0 0;">
        <el-pagination
          :current-page="queryParam.page"
          :page-size="queryParam.limit"
          :page-sizes="[10, 20, 30, 40]"
          :total="total"
          background
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange">
        </el-pagination>
      </div>
    </el-card>
    <a-modal
      :title="modal.title"
      :visible="modal.visible"
      maskClosable
      width="95%"
      @cancel="modal.visible = false"
      @ok="handleOk"
    >
      <a-form :form="modal.form" :label-col="{ span: 3 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="分类">
          <a-tree-select
            v-model="modal.form.categoryId"
            :replaceFields="{children:'children', title:'name', key:'id', value: 'id' }"
            :tree-data="treeData"
            placeholder="请选择分类"
            tree-default-expand-all
            :dropdownMatchSelectWidth = "true"
            :dropdown-style="{ maxHeight: '300px', overflow: 'auto' }"
          >
            <span slot="title" slot-scope="{ key, value }" style="color: #08c">
              {{ value }}
            </span>
          </a-tree-select>
        </a-form-item>
        <a-form-item label="封面">
          <a-upload
            :action="uploadApi"
            :show-upload-list="false"
            accept="image/png, image/jpeg"
            class="avatar-uploader"
            list-type="picture-card"
            name="file"
            @change="handleChange">
            <img
              v-if="coverFileList && coverFileList[0]"
              :src="coverFileList[0].response.data.src"
              alt="avatar"
              height="150"
              width="150" />
            <div v-else>
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item label="标题">
          <a-input v-model="modal.form.title" placeholder="请输入标题" />
        </a-form-item>
<!--        <a-form-item label="报考费用">
          <a-input v-model="modal.form.fee" placeholder="请输入报考费用" />
        </a-form-item> -->
        
        <a-form-item label="报考费用">
          <a-input-number :min="0" :precision="2" v-model="modal.form.fee" placeholder="报考费用" 
          :style="{ width: '30%', textAlign: 'center', display: 'inline-block' }" />
          <span style="padding-left: 20px;">抵扣金币：</span>
          <a-input-number :min="0" :precision="0" v-model="modal.form.discountCoin" placeholder="抵扣金币" 
          :style="{ width: '30%', textAlign: 'center', display: 'inline-block' }" />
        </a-form-item>
        
        <a-form-item label="考试时间">
          <a-date-picker
            v-model="modal.form.examDate"
            format="YYYY-MM-DD"
            placeholder="请选择考试时间"
            valueFormat="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item label="简介">
          <a-textarea
            v-model="modal.form.brief"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            placeholder="请输入简介" />
        </a-form-item>
        <a-form-item label="考试区域">
          <el-cascader
            v-model="modal.form.city"
            :options="areaData"
            :props="{value: 'id',label: 'name',children: 'children',emitPath: false}"
            :show-all-levels="false"
            filterable
            size="medium"></el-cascader>
        </a-form-item>
        <a-form-item label="考试地点">
          <a-textarea
            v-model="modal.form.address"
            :auto-size="{ minRows: 2, maxRows: 6 }"
            placeholder="请输入考试详细地点" />
        </a-form-item>
        <a-form-item label="详情">
          <wang-editor
            ref="wangEditorRef"
            :content="modal.form.detail"
            :uploadApi="uploadApi"
            @change="catchData"></wang-editor>
        </a-form-item>
        <a-form-item label="课程类型">
          <a-select v-model="modal.form.classType" placeholder="请选择课程类型">
            <a-select-option v-for="(item,index) in classTypeList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="考试状态">
          <a-select v-model="modal.form.examState" placeholder="请选择考试状态">
            <a-select-option v-for="(item,index) in examStateList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="标签">
          <el-tag
            v-for="(item,index) in dynamicTags"
            :key="index"
            :disable-transitions="false"
            closable
            style="margin-right: 15px"
            @close="handleClose(item)">
            {{ item }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            maxlength="5"
            size="small"
            @blur="handleInputConfirm"
            @keyup.enter.native="handleInputConfirm"
          >
          </el-input>
          <el-button v-else class="button-new-tag" size="small" @click="showInput">新增标签</el-button>
        </a-form-item>
        <a-form-item label="状态">
          <a-select v-model="modal.form.state" placeholder="请选择状态">
            <a-select-option v-for="(item,index) in stateList" :key="index" :value="item.value">
              {{ item.label }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="排序号">
          <a-input v-model="modal.form.sortOrder" placeholder="请输入排序号" />
        </a-form-item>
      </a-form>
    </a-modal>
    <Preview ref="createModal" :model="mdl" :visible="showPreview" @cancel="showPreview = false" />
  </page-header-wrapper>
</template>

<script>
import {
  addPaiContentCertificate,
  getActiveTree as getTree,
  getTablePaiContentCertificate,
  getTreeArea,
  paiContentCertificateActive,
  paiContentCertificateFrozen,
  updatePaiContentCertificate
} from '@/api/contentCenter'
import api from '@/api/banner'
import WangEditor from '@/components/Editor/WangEditor.vue'
import Preview from '@/pages/knowledge/modules/Preview.vue'

const baseApi = process.env.VUE_APP_API_BASE_URL

export default {
  name: 'Index',
  components: { Preview, WangEditor },
  data () {
    return {
      dynamicTags: [],
      inputVisible: false,
      inputValue: '',
      showPreview: false,
      mdl: {
        title: '预览',
        content: '',
        sumView: '详情'
      },
      examStateList: [
        {
          value: 0,
          label: '未开考'
        }, {
          value: 1,
          label: '进行中'
        }, {
          value: 2,
          label: '已结束'
        }
      ],
      classTypeList: [
        {
          value: 0,
          label: '无'
        }, {
          value: 1,
          label: '线上课'
        }, {
          value: 2,
          label: '线下课'
        }
      ],
      stateList: [
        {
          value: 1,
          label: '激活'
        }, {
          value: 2,
          label: '冻结'
        }
      ],
      video: {
        visible: false,
        url: ''
      },
      queryParam: {
        page: 1,
        limit: 20
      },
      total: 0,
      typeId: 5,
      modal: {
        visible: false,
        title: '',
        form: {}
      },
      fileList: [],
      bannerLoading: false,
      coverFileList: [],
      uploadApi: baseApi + api.upload,
      treeData: [],
      tableData: [],
      areaData: []
    }
  },
  mounted () {
    this.getTable()
    this.getTree()
  },
  methods: {
    handleClose (tag) {
      this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1)
    },
    showInput () {
      if (this.dynamicTags.length === 3) {
        this.inputVisible = false
        this.$message({
          message: '最多只能添加3个标签',
          type: 'warning'
        })
        return
      }
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm () {
      const inputValue = this.inputValue
      if (inputValue) {
        this.dynamicTags.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    deleteChildren (arr) {
      const list = arr
      for (let i = list.length; i--; i > 0) {
        if (list[i].children) {
          if (list[i].children.length) {
            this.deleteChildren(list[i].children)
          } else {
            delete list[i].children
          }
        }
      }
      return arr
    },
    getTreeArea () {
      getTreeArea().then(res => {
        this.areaData = this.deleteChildren(res.data)
      })
    },
    handlePreview (record) {
      this.showPreview = true
      this.mdl.content = record.detail
    },
    catchData (content) {
      this.modal.form.detail = content
    },
    query () {
      this.queryParam.page = 1
      this.getTable()
    },
    reset () {
      this.queryParam = {
        page: 1,
        limit: 20
      }
      this.getTable()
    },
    handleSizeChange (val) {
      this.queryParam.limit = val
      this.getTable()
    },
    handleCurrentChange (val) {
      this.queryParam.page = val
      this.getTable()
    },
    handleStatus (record) {
      this.$confirm(`您确定要${record.state === 1 ? '冻结' : '激活'}吗？`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (record.state === 1) {
          paiContentCertificateFrozen({ id: record.id, state: 2 }).then(() => {
            this.$message.success('冻结成功')
            this.getTable()
          })
        } else {
          paiContentCertificateActive({ id: record.id, state: 1 }).then(() => {
            this.$message.success('激活成功')
            this.queryParam.page = 1
            this.getTable()
          })
        }
      }).catch(() => {
      })
    },
    getTable () {
      getTablePaiContentCertificate(this.queryParam).then(res => {
        this.tableData = res.data.records
        this.total = parseInt(res.data.total)
      })
    },
    getTree () {
      getTree({ page: 1, limit: 100000 }, this.typeId).then(res => {
        this.treeData = JSON.parse(JSON.stringify(res.data))
      })
    },
    handleOk () {
      // 金币抵扣不能大于费用
      if(this.modal.form.discountCoin > this.modal.form.fee){
        this.$message.error('抵扣金币不能大于费用')
        return
      }
      if (this.modal.form.id) {
        updatePaiContentCertificate({ label: this.dynamicTags.length > 0 ? this.dynamicTags.join() : '', ...this.modal.form }).then(res => {
          this.$message.success(res.msg)
          this.modal.form = {}
          this.modal.visible = false
          this.queryParam.page = 1
          this.getTable()
        })
      } else {
        addPaiContentCertificate({ label: this.dynamicTags.length > 0 ? this.dynamicTags.join() : '', ...this.modal.form }).then(res => {
          this.$message.success(res.msg)
          this.modal.form = {}
          this.modal.visible = false
          this.queryParam.page = 1
          this.getTable()
        })
      }
    },
    handleAdd () {
      this.modal.form = {
        categoryId: '',
        brief: '',
        cover: '',
        address: '',
        sortOrder: '100',
        typeId: this.typeId,
        title: '',
        detail: '',
        classType: '',
        examState: '',
        fee: '',
        examDate: '',
        city: '',
        state: 1,
        discountCoin: ''
      }
      this.coverFileList = null
      this.modal.visible = true
      this.modal.title = '新增'
      this.dynamicTags = []
      this.$nextTick(res => {
        this.$refs.wangEditorRef.wangEditorReset('')
      })
      this.getTreeArea()
    },
    handleEdit (record) {
      const data = JSON.parse(JSON.stringify(record))
      this.dynamicTags = data.labels
      this.modal.form = {
        categoryId: data.categoryId,
        brief: data.brief,
        cover: data.cover,
        sortOrder: data.sortOrder,
        typeId: data.typeId,
        title: data.title,
        state: data.state,
        detail: data.detail,
        address: data.address,
        city: data.city,
        classType: data.classType,
        examState: data.examState,
        fee: data.fee,
        examDate: data.examDate,
        customerName: data.customerName,
        id: data.id,
        discountCoin: data.discountCoin
      }
      this.coverFileList = [
        {
          response: {
            data: {
              src: data.cover
            }
          }
        }
      ]
      this.modal.visible = true
      this.modal.title = '编辑'
      this.$nextTick(res => {
        this.$refs.wangEditorRef.wangEditorReset(data.detail)
      })
      this.getTreeArea()
    },
    handleCopy (record) {
      const data = JSON.parse(JSON.stringify(record))
      this.dynamicTags = data.labels
      this.modal.form = {
        categoryId: data.categoryId,
        brief: data.brief,
        cover: data.cover,
        sortOrder: data.sortOrder,
        typeId: data.typeId,
        title: data.title,
        state: data.state,
        detail: data.detail,
        address: data.address,
        city: data.city,
        classType: data.classType,
        examState: data.examState,
        fee: data.fee,
        examDate: data.examDate,
        customerName: data.customerName,
        discountCoin: data.discountCoin
      }
      this.coverFileList = [
        {
          response: {
            data: {
              src: data.cover
            }
          }
        }
      ]
      this.modal.visible = true
      this.modal.title = '复制'
      this.$nextTick(res => {
        this.$refs.wangEditorRef.wangEditorReset(data.detail)
      })
      this.getTreeArea()
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.bannerLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.coverFileList = info.fileList.slice(-1)
        this.modal.form.cover = this.coverFileList[0].response.data.src
        this.bannerLoading = false
      }
    }
  }
}
</script>

<style lang="less" scoped>
.view-video {
  position: relative;

  .close {
    position: absolute;
    right: 15px;
    top: 0;
    cursor: pointer;
  }
}

/deep/.ant-modal-body {
  max-height: calc(80vh - 150px);
  overflow-y: auto;
  &::-webkit-scrollbar {
    width: 6px;
    /*高宽分别对应横竖滚动条的尺寸*/
    height: 1px;
  }

  &::-webkit-scrollbar-thumb {
    // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    background: #e3e3e6;
    border-radius: 6px;
  }

  &::-webkit-scrollbar-track {
    background: transparent;
    // -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
    border-radius: 5px;
  }
}
</style>
